package controllers

import (
	"fmt"
	"github.com/jsoq/goblog/app/models/user"
	"github.com/jsoq/goblog/app/requests"
	"github.com/jsoq/goblog/pkg/auth"
	"github.com/jsoq/goblog/pkg/flash"
	"github.com/jsoq/goblog/pkg/session"
	"github.com/jsoq/goblog/pkg/view"
	"net/http"
)

type AuthController struct {


}

//Register
func (*AuthController) Register(w http.ResponseWriter, r *http.Request)  {
	view.RenderSimple(w, view.D{}, "auth.register")
}


// DoRegister 处理注册逻辑
func (*AuthController) DoRegister(w http.ResponseWriter, r *http.Request) {

	// 1. 初始化数据
	_user := user.User{
		Name:            r.PostFormValue("name"),
		Email:           r.PostFormValue("email"),
		Password:        r.PostFormValue("password"),
		PasswordComfirm: r.PostFormValue("password_comfirm"),
	}

	errs := requests.ValidateRegistrationForm(_user)

	if len(errs) > 0 {
		//表单不通过 重新显示表单
		// 3. 表单不通过 —— 重新显示表单
		view.RenderSimple(w, view.D{
			"Errors": errs,
			"User":   _user,
		}, "auth.register")
	}else{
		_user.Create()
		if _user.ID > 0 {
			// 登录用户并跳转到首页
			flash.Success("恭喜您注册成功！")
			auth.Login(_user)
			http.Redirect(w, r, "/", http.StatusFound)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "创建文章失败，请联系管理员")
		}
	}
}

func (*AuthController) Login (w http.ResponseWriter, r *http.Request) {
	session.Put("uid","1")
	view.RenderSimple(w, view.D{}, "auth.login")
}

//DoLogin 处理登录表单提交
func (*AuthController) DoLogin(w http.ResponseWriter, r *http.Request) {
	//初始化表单数据
	email := r.PostFormValue("email")
	password := r.PostFormValue("password")

	//2尝试登录
	if err := auth.Attempt(email, password); err == nil {
		//登录成功
		flash.Success("欢迎回来！")
		http.Redirect(w, r, "/", http.StatusFound)
	}else {
		view.RenderSimple(w, view.D{
			"Error": err.Error(),
			"Email": email,
			"Pssword":password,
		},"auth.login")
	}
}

func (*AuthController) Logout(w http.ResponseWriter, r *http.Request) {
	auth.Logout()
	flash.Success("您已退出登录")
	http.Redirect(w, r, "/", http.StatusFound)
}




